package com.sk.bilibili.view.diy;

import static com.sk.bilibili.utils.StringUtils.str;

import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.sk.bilibili.R;
import com.sk.bilibili.bean.Danmu;
import com.sk.bilibili.bean.Live;
import com.sk.bilibili.callBack.DanmuCallBack;
import com.sk.bilibili.databinding.ViewLivePlayerBinding;
import com.sk.bilibili.event.LiveEvent;
import com.sk.bilibili.other.BiliBiliDanmuParser;
import com.sk.bilibili.utils.DanmuUtils;

import org.greenrobot.eventbus.EventBus;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.parser.IDataSource;
import master.flame.danmaku.danmaku.parser.android.BiliDanmukuParser;
import master.flame.danmaku.danmaku.parser.android.JSONSource;

public class LivePlayerView extends ConstraintLayout {

    public LivePlayerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        bind = ViewLivePlayerBinding.inflate(LayoutInflater.from(context), this, true);
        initData();
        initView();
        bindEvent();
    }

    private void initView() {
        bind.pvShow.setPlayer(player);
        bind.pvShow.setUseController(false);
    }

    private ViewLivePlayerBinding bind;
    private DanmakuContext danmakuContext;
    private boolean play;
    private String url;
    private boolean fullScreen;
    private boolean danmu;
    private ExoPlayer player;
    private static final int HIDE_CONTROLLER =1;
    private Handler handler=new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            bind.clController.setVisibility(GONE);
        }
    };

    private void bindEvent() {
        bind.ivPlayerBack.setOnClickListener(v -> EventBus.getDefault().post(LiveEvent.exitEvent()));
        bind.ivPlayerMore.setOnClickListener(v -> EventBus.getDefault().post(LiveEvent.moreEvent()));
        bind.ivPlayPause.setOnClickListener(v -> playOrPause());
        bind.ivRefresh.setOnClickListener(v -> {
            player.setMediaItem(MediaItem.fromUri(url));
            player.prepare();
            player.play();
            play = true;
        });
        bind.ivFullscreen.setOnClickListener(v->changeScreen());
        bind.ivDanmu.setOnClickListener(v->{
            danmu=!danmu;
            bind.ivDanmu.setImageResource(danmu?R.drawable.full_danmu_open:R.drawable.full_danmu_close);
        });
        bind.ivSend.setOnClickListener(v->sendDanmu(bind.etSend));
        bind.dsvShow.setOnClickListener(v -> {
            bind.clController.setVisibility(VISIBLE);
            handler.removeMessages(HIDE_CONTROLLER);
            handler.sendEmptyMessageDelayed(HIDE_CONTROLLER,7000);
        });
        bind.clController.setOnClickListener(v -> {
            handler.removeMessages(HIDE_CONTROLLER);
            bind.clController.setVisibility(GONE);
        });
    }

    private void sendDanmu(EditText send) {
        Danmu danmu = new Danmu();
        bind.etSend.setText("");
        danmu.setType(DanmuUtils.getRandomType());
        danmu.setContent(str(send));
        danmu.setColor(DanmuUtils.getRandomColor());
        sendDanmu(danmu);
    }

    public void changeScreen(){
        fullScreen=!fullScreen;
        bind.ivFullscreen.setImageResource(fullScreen?R.drawable.exit_fullscreen:R.drawable.fullscreen);
        bind.llShow.setVisibility(fullScreen?VISIBLE:GONE);
        EventBus.getDefault().post(LiveEvent.screenEvent(fullScreen));
    }

    private void initData() {
        bind.dsvShow.setCallback((DanmuCallBack) () -> bind.dsvShow.start());
        danmakuContext = DanmakuContext.create();
        bind.dsvShow.enableDanmakuDrawingCache(true);
        bind.dsvShow.prepare(new BiliBiliDanmuParser(), danmakuContext);
        play = false;
        fullScreen=false;
        danmu=true;
        player = new ExoPlayer.Builder(getContext()).build();
    }

    public void play(Live live) {
        url = live.getUrl();
        player.setMediaItem(MediaItem.fromUri(url));
        player.prepare();
        player.play();
        bind.tvPlayerTitle.setText(live.getTitle());
        play = true;
    }

    public void sendDanmu(Danmu danmu) {
        if(!this.danmu)return;
        danmu.setTime((float) bind.dsvShow.getCurrentTime());
        BaseDanmaku danmaku = DanmuUtils.toDanmaku(danmu, danmakuContext, false);
        bind.dsvShow.addDanmaku(danmaku);
    }

    public void onDestroy() {
        bind.dsvShow.stop();
        bind.dsvShow.release();
        handler.removeMessages(HIDE_CONTROLLER);
        player.release();
        player=null;
    }

    public void playOrPause() {
        play = !play;
        if (play) {
            player.play();
            bind.dsvShow.resume();
        } else {
            player.pause();
            bind.dsvShow.pause();
        }
        bind.ivPlayPause.setImageResource(play? R.drawable.pause:R.drawable.play);
    }

    public void pause() {
        if (play) playOrPause();
    }

    public void resume() {
        if (!play) playOrPause();
    }

    public boolean exitFullScreen() {
        if(!fullScreen)return false;
        changeScreen();
        return true;
    }

}